<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="评论ID" prop="commentId">
        <el-input
          v-model="queryParams.commentId"
          placeholder="请输入评论ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="回复者ID" prop="publisherId">
        <el-input
          v-model="queryParams.publisherId"
          placeholder="请输入回复者ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="回复者昵称" prop="publisherNickname">
        <el-input
          v-model="queryParams.publisherNickname"
          placeholder="请输入昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="回复时间" prop="replyTime">
        <el-date-picker clearable
          v-model="queryParams.replyTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:commentReplies:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:commentReplies:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:commentReplies:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:commentReplies:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="commentRepliesList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="回复ID" align="center" prop="replyId" width="80" />
      <el-table-column label="评论ID" align="center" prop="commentId" width="100" />
      <el-table-column label="回复者" align="center" min-width="150">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center;">
            <el-image
              v-if="scope.row.publisherAvatar"
              :src="scope.row.publisherAvatar"
              :preview-src-list="[scope.row.publisherAvatar]"
              style="width: 30px; height: 30px; border-radius: 50%; margin-right: 8px;"
              fit="cover"
            />
            <span>{{ scope.row.publisherNickname }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="回复内容" align="center" prop="replyContent" min-width="200" show-overflow-tooltip />
      <el-table-column label="回复图片" align="center" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.replyImages && formatImageList(scope.row.replyImages).length > 0" style="display: flex; justify-content: center; gap: 5px;">
            <el-image
              v-for="(img, index) in formatImageList(scope.row.replyImages).slice(0, 3)"
              :key="index"
              :src="img"
              :preview-src-list="formatImageList(scope.row.replyImages)"
              style="width: 40px; height: 40px; border-radius: 4px;"
              fit="cover"
            />
            <span v-if="formatImageList(scope.row.replyImages).length > 3">+{{ formatImageList(scope.row.replyImages).length - 3 }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="点赞" align="center" prop="likeCount" width="80" />
      <el-table-column label="回复时间" align="center" prop="replyTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.replyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" min-width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status" type="success" size="small">
            {{ formatJsonField(scope.row.status) }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:commentReplies:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:commentReplies:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评论回复对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="评论ID" prop="commentId">
                  <el-input v-model="form.commentId" placeholder="请输入评论ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="父回复ID" prop="parentReplyId">
                  <el-input v-model="form.parentReplyId" placeholder="请输入父回复ID（一级回复留空）" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="点赞数量" prop="likeCount">
                  <el-input-number v-model="form.likeCount" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="回复时间" prop="replyTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.replyTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择回复时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 回复内容 -->
          <el-tab-pane label="回复内容" name="content">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="回复内容" prop="replyContent">
                  <el-input 
                    v-model="form.replyContent" 
                    type="textarea"
                    :rows="6"
                    placeholder="请输入回复内容"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="回复图片" prop="replyImages">
                  <image-upload 
                    v-model="form.replyImages" 
                    :limit="9"
                    :fileSize="5"
                    :isShowTip="true"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 回复者信息 -->
          <el-tab-pane label="回复者信息" name="publisher">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="回复者ID" prop="publisherId">
                  <el-input v-model="form.publisherId" placeholder="请输入回复者ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="回复者昵称" prop="publisherNickname">
                  <el-input v-model="form.publisherNickname" placeholder="请输入回复者昵称" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="回复者头像" prop="publisherAvatar">
                  <image-upload 
                    v-model="form.publisherAvatar" 
                    :limit="1"
                    :fileSize="2"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 扩展信息 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="回复状态" prop="status">
                  <el-input 
                    v-model="form.status" 
                    type="textarea" 
                    :rows="3"
                    placeholder='请输入JSON格式，例如：{"status":"正常","checked":"已审核"}'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="扩展数据" prop="extraData">
                  <el-input 
                    v-model="form.extraData" 
                    type="textarea" 
                    :rows="5"
                    placeholder='请输入JSON格式的扩展数据'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCommentReplies, getCommentReplies, delCommentReplies, addCommentReplies, updateCommentReplies } from "@/api/system/commentReplies";
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "CommentReplies",
  components: {
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 评论回复表格数据
      commentRepliesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前选中的标签页
      activeTab: 'basic',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        commentId: null,
        replyContent: null,
        replyImages: null,
        publisherId: null,
        publisherAvatar: null,
        publisherNickname: null,
        replyTime: null,
        likeCount: null,
        parentReplyId: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        commentId: [
          { required: true, message: "评论ID不能为空", trigger: "blur" }
        ],
        replyContent: [
          { required: true, message: "回复内容不能为空", trigger: "blur" }
        ],
        publisherId: [
          { required: true, message: "回复者用户ID不能为空", trigger: "blur" }
        ],
        publisherNickname: [
          { required: true, message: "回复者昵称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 格式化JSON字段显示 */
    formatJsonField(jsonData) {
      if (!jsonData) return '-';
      try {
        const data = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;
        if (typeof data === 'object') {
          return data.status || data.name || data.type || JSON.stringify(data);
        }
        return jsonData;
      } catch (e) {
        return jsonData;
      }
    },
    /** 格式化图片列表 */
    formatImageList(images) {
      if (!images) return [];
      try {
        const imageArray = typeof images === 'string' ? JSON.parse(images) : images;
        return Array.isArray(imageArray) ? imageArray : [];
      } catch (e) {
        return [];
      }
    },
    /** 查询评论回复列表 */
    getList() {
      this.loading = true;
      listCommentReplies(this.queryParams).then(response => {
        this.commentRepliesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        replyId: null,
        commentId: null,
        replyContent: null,
        replyImages: null,
        publisherId: null,
        publisherAvatar: null,
        publisherNickname: null,
        replyTime: null,
        likeCount: null,
        parentReplyId: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.replyId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.activeTab = 'basic';
      this.open = true;
      this.title = "添加评论回复";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'basic';
      const replyId = row.replyId || this.ids
      getCommentReplies(replyId).then(response => {
        this.form = response.data;
        
        // 处理图片字段：JSON数组转逗号分隔字符串用于ImageUpload组件
        if (this.form.replyImages) {
          const urls = typeof this.form.replyImages === 'string' 
            ? JSON.parse(this.form.replyImages) 
            : this.form.replyImages;
          this.form.replyImages = Array.isArray(urls) ? urls.join(',') : urls;
        }
        
        // 处理JSON字段：对象转字符串用于textarea显示
        if (this.form.status && typeof this.form.status === 'object') {
          this.form.status = JSON.stringify(this.form.status, null, 2);
        }
        if (this.form.extraData && typeof this.form.extraData === 'object') {
          this.form.extraData = JSON.stringify(this.form.extraData, null, 2);
        }
        
        this.open = true;
        this.title = "修改评论回复";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 深拷贝表单数据
          const submitForm = JSON.parse(JSON.stringify(this.form));
          
          // 处理图片字段：逗号分隔字符串转JSON数组用于提交
          if (submitForm.replyImages && typeof submitForm.replyImages === 'string') {
            const urlArray = submitForm.replyImages.split(',').filter(url => url.trim());
            submitForm.replyImages = urlArray.length > 0 ? JSON.stringify(urlArray) : null;
          }
          
          // 处理JSON字段：字符串转对象用于提交
          if (submitForm.status && typeof submitForm.status === 'string') {
            try {
              submitForm.status = submitForm.status.trim() 
                ? JSON.parse(submitForm.status) 
                : null;
            } catch (e) {
              this.$modal.msgError("回复状态JSON格式不正确");
              return;
            }
          }
          if (submitForm.extraData && typeof submitForm.extraData === 'string') {
            try {
              submitForm.extraData = submitForm.extraData.trim() 
                ? JSON.parse(submitForm.extraData) 
                : null;
            } catch (e) {
              this.$modal.msgError("扩展数据JSON格式不正确");
              return;
            }
          }
          
          if (submitForm.replyId != null) {
            updateCommentReplies(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCommentReplies(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const replyIds = row.replyId || this.ids;
      this.$modal.confirm('是否确认删除评论回复编号为"' + replyIds + '"的数据项？').then(function() {
        return delCommentReplies(replyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/commentReplies/export', {
        ...this.queryParams
      }, `commentReplies_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}

::v-deep .el-tabs--border-card {
  box-shadow: none;
}

::v-deep .el-tabs__content {
  padding: 20px;
}
</style>
